package com.ruoyi.common.utils.date;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.sql.Timestamp;

@Component
public class DateJsonConverter {

  public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
  public static final String SHORT_DATE_FORMAT = "yyyy-MM-dd";

  public String toJson(Object value) {
    if (value.getClass().equals(Timestamp.class)) {
      JSONObject.DEFFAULT_DATE_FORMAT = DATE_FORMAT; // 设置时间格式
    }
    if (value.getClass().equals(Date.class) || value.getClass().equals(java.util.Date.class)) {
      JSONObject.DEFFAULT_DATE_FORMAT = SHORT_DATE_FORMAT; // 设置日期格式
    }
    value =
        JSONObject.toJSONString(value, SerializerFeature.WriteDateUseDateFormat).replace("\"", "");
    return value.toString();
  }

  public String toJson(Object value, String format) {
    JSONObject.DEFFAULT_DATE_FORMAT = StringUtils.isEmpty(format) ? SHORT_DATE_FORMAT : format;
    value =
        JSONObject.toJSONString(value, SerializerFeature.WriteDateUseDateFormat).replace("\"", "");
    return value.toString();
  }
}
